#include "CCefResourceHandler.h"
#include "CCefHandler.h"
#include "CCefURLRequestClient.h"

CCefResourceHandler::CCefResourceHandler() : _offset(0)
{
}

bool CCefResourceHandler::ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback)
{
	//1. Start the request using WebRequest
	//2. Return True to handle the request
	//3. Once response headers are ready call
	//   callback.Continue()
	_responseHeadersReadyCallback = callback;

	_webRequestClient = new CCefURLRequestClient(_frame);
	_webRequestClient->_resourceHandler = this;
	request->SetFlags(UR_FLAG_ALLOW_STORED_CREDENTIALS);

	//To skip cache :
	//| request.SetFlags(cefpython.Request.Flags["SkipCache"])
	//Must keep a strong reference to the WebRequest() object.
	_webRequest = CefURLRequest::Create(request, _webRequestClient, nullptr);

	return true;
}

void CCefResourceHandler::GetResponseHeaders(CefRefPtr<CefResponse> response, int64& response_length, CefString& redirectUrl)
{
	CefRefPtr<CefResponse> webResponse = _webRequestClient->_response;

	if (webResponse != nullptr)
	{
		CefResponse::HeaderMap headerMap;
		webResponse->GetHeaderMap(headerMap);
		response->SetHeaderMap(headerMap);
		response->SetStatus(webResponse->GetStatus());
		response->SetStatusText(webResponse->GetStatusText());
		CefString cefstr = webResponse->GetMimeType();
		if (!cefstr.empty())
		{
			response->SetMimeType(webResponse->GetMimeType());
		}
	}

	response_length = _content.size();
	_offset = 0;
}

bool CCefResourceHandler::ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr<CefCallback> callback)
{
	//here fill what response data will be return!
	size_t size = _content.size();

	if (_offset < size)
	{
		int transfer_size = min(bytes_to_read, static_cast<int>(size - _offset));

		memcpy(data_out, _content.c_str() + _offset, transfer_size);
		_offset += transfer_size;

		bytes_read = transfer_size;//output

		auto pDataOut = (char*)data_out;
		return true;
	}
	return false;
}
